package com.atguigu.api;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: xxx
 * @time: 2021-03-14 20:10
 * @author: baojinlong
 **/
public class ThreadDemo01 {

    private static Lock lock = new ReentrantLock(true);

    private static Condition ca = lock.newCondition();
    private static Condition cb = lock.newCondition();
    private static Condition cc = lock.newCondition();

    private static volatile int idx = 0;

    /**
     * 上述示例定义了 3 个线程类 A、B 和 C，并按照 A -> B -> C
     * 的顺序进行组织，各个线程在调用 Lock#lock 方法获取到锁之后会先尝试通知后继线程（将对应的线程移入到同步队列），
     * 然后对idx变量进行累加并打印，接着进入等待状态并释放资源，方法Lock#unlock接下来会调度位于同步队列队头结点的线程继续执行。
     */
    private static class A implements Runnable {

        @Override
        public void run() {
            try {
                lock.lock();
                for (int i = 0; i < 10; i++) {
                    cb.signalAll();
                    System.out.println("a: " + (++idx));
                    ca.await();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    private static class B implements Runnable {

        @Override
        public void run() {
            try {
                lock.lock();
                for (int i = 0; i < 10; i++) {
                    cc.signalAll();
                    System.out.println("b: " + (++idx));
                    cb.await();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    private static class C implements Runnable {

        @Override
        public void run() {
            try {
                lock.lock();
                for (int i = 0; i < 10; i++) {
                    ca.signalAll();
                    System.out.println("c: " + (++idx));
                    cc.await();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        new Thread(new A()).start();
        new Thread(new B()).start();
        new Thread(new C()).start();
    }
}
